# -*- coding: utf-8 -*-
# 重要: 如果运行不了,请及时更新settings中的request headers中的authorization 值
import json
from scrapy import Spider, Request
from zhihuuser.items import ZhihuuserItem


class ZhihuSpider(Spider):
    name = 'zhihu'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['http://www.zhihu.com/']

    start_user = 'excited-vczh'
    # 用户信息列表
    user_url = "https://www.zhihu.com/api/v4/members/{url_token}?include={include}"
    user_query  = "locations,employments,gender,educations,business,voteup_count,thanked_Count,follower_count,following_count,cover_url,following_topic_count,following_question_count,following_favlists_count,following_columns_count,avatar_hue,answer_count,articles_count,pins_count,question_count,columns_count,commercial_question_count,favorite_count,favorited_count,logs_count,included_answers_count,included_articles_count,included_text,message_thread_token,account_status,is_active,is_bind_phone,is_force_renamed,is_bind_sina,is_privacy_protected,sina_weibo_url,sina_weibo_name,show_sina_weibo,is_blocking,is_blocked,is_following,is_followed,is_org_createpin_white_user,mutual_followees_count,vote_to_count,vote_from_count,thank_to_count,thank_from_count,thanked_count,description,hosted_live_count,participated_live_count,allow_message,industry_category,org_name,org_homepage,badge[?(type=best_answerer)].topics"

    # 用户关注的人列表
    followees_url = "https://www.zhihu.com/api/v4/members/{url_token}/followees?include={include}&offset={offset}&limit={limit}"
    followees_query = "data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topic"

    # 用户粉丝列表
    followers_url = "https://www.zhihu.com/api/v4/members/{url_token}/followers?include={include}&offset={offset}&limit={limit}"
    followers_query = "data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics"

    def start_requests(self):
        yield Request(url=self.user_url.format(url_token=self.start_user, include=self.user_query), callback=self.parse_user)
        yield Request(url=self.followees_url.format(url_token=self.start_user, include=self.followees_query, offset=0, limit=20), callback=self.parse_followee)
        yield Request(url=self.followers_url.format(url_token=self.start_user, include=self.followers_query, offset=0, limit=20), callback=self.parse_follower)

    def parse_user(self, response):
        result = json.loads(response.text)
        item = ZhihuuserItem()
        for field in item.fields:
            if field in result.keys():
                item[field] = result.get(field)
        yield item
        yield Request(url=self.followees_url.format(url_token=result.get('url_token'), include=self.followees_query, offset=0, limit=20), callback=self.parse_followee)
        yield Request(url=self.followers_url.format(url_token=result.get('url_token'), include=self.followers_query, offset=0, limit=20), callback=self.parse_follower)

    def parse_followee(self, response):
        results = json.loads(response.text)

        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(url_token=result.get('url_token'), include=self.user_query), callback=self.parse_user)

        if 'paging' in results.keys() and results.get('paging').get('is_end') == False:
            next_page = results.get('paging').get('next')
            yield Request(next_page, callback=self.parse_followee)

    def parse_follower(self, response):
        results = json.loads(response.text)

        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(url_token=result.get('url_token'), include=self.user_query), callback=self.parse_user)

        if 'paging' in results.keys() and results.get('paging').get('is_end') == False:
            next_page = results.get('paging').get('next')
            yield Request(next_page, callback=self.parse_follower)